package com.yxlgateway.config;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: yxl
 * @since: 2022-03-27
 **/
@Slf4j
@ChannelHandler.Sharable
public class MySocketException extends ChannelDuplexHandler {

    private final Map<String,Object> exceptionMap = new ConcurrentHashMap<>();

    public static final MySocketException handler = new MySocketException();

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof RuntimeException){
            ByteBuf byteBuf = ctx.alloc().buffer();
            exceptionMap.put("errorCode",-1000);
            exceptionMap.put("errorMessage",cause.getMessage());
            exceptionMap.put("breakErrorTime",new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm:ss").format(new Date()));
            byteBuf.writeBytes(exceptionMap.toString().getBytes(StandardCharsets.UTF_8));
            ctx.channel().writeAndFlush(new TextWebSocketFrame(byteBuf));
        }
    }
}
